package handler

import (
	"strconv"

	"awesomeProject/app/model"
	"awesomeProject/app/verify"
	"github.com/gin-gonic/gin"

	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/app/service"
)

type RoleHandler struct{}

var roleSrv service.RoleSrv

// Pagination 分页列表
func (r *RoleHandler) Pagination(ctx *gin.Context) {
	var req request.RolePagination
	_ = ctx.Bind(&req)
	if err := verify.RolePagination(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	response.Result(ctx, roleSrv.Pagination(req))
	return
}

// Create 创建
func (r *RoleHandler) Create(ctx *gin.Context) {
	var req request.RoleCreate
	_ = ctx.Bind(&req)
	user, _ := ctx.Get("user")
	if err := verify.RoleCreate(&req, user.(model.User).CompanyId); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	response.Result(ctx, roleSrv.Create(req, user.(model.User)))
	return
}

// Update 更新
func (r *RoleHandler) Update(ctx *gin.Context) {
	var req request.RoleUpdate
	_ = ctx.Bind(&req)
	if err := verify.RoleUpdate(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	id, _ := strconv.Atoi(ctx.Param("id"))
	user, _ := ctx.Get("user")
	// 执行更新
	response.Result(ctx, roleSrv.Update(uint(id), req, user.(model.User)))
	return
}

// Permissions 所有权限
func (r *RoleHandler) Permissions(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, roleSrv.Permissions(uint(id)))
	return
}

// Show 查看
func (r RoleHandler) Show(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, roleSrv.Show(uint(id)))
	return
}

// Del 删除
func (r RoleHandler) Del(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, roleSrv.Del(uint(id)))
	return
}

// Menus 角色菜单权限
func (r RoleHandler) Menus(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	response.Result(ctx, roleSrv.Menus(uint(id)))
	return
}

// AddMenusForRole 角色菜单权限分配
func (r RoleHandler) AddMenusForRole(ctx *gin.Context) {
	id, _ := strconv.Atoi(ctx.Param("id"))
	var req request.AssignMenus
	_ = ctx.Bind(&req)
	if err := verify.AddMenusForRole(&req); err != nil {
		response.Result(ctx, response.ErrInvalidParam.SetMsg(err.Error()))
		return
	}
	response.Result(ctx, roleSrv.AddMenusForRole(uint(id), req.Checked, req.HalfChecked))
	return
}
